﻿using System;
using System.Collections.Generic;
using System.IO;

namespace UlsLogViewer.Entities
{
    public class LogFile
    {
        public FileSystemInfo File { get; internal set; }

        public string FullName { get; internal set; }

        public DateTime CreationTime { get; internal set; }

        private List<LogEntry> _logEntries;
        public List<LogEntry> LogEntries
        {
            get
            {
                if (_logEntries == null)
                {
                    LoadLogEntries();
                }
                return _logEntries;
            }
            internal set { _logEntries = value; }
        }
 
        public LogFile(FileSystemInfo fileInfo)
        {
            File = fileInfo;
            FullName = fileInfo.FullName;
            CreationTime = fileInfo.CreationTime;
        }

        public void LoadLogEntries()
        {
            LogEntries = new List<LogEntry>();
            using (var logFile = new FileStream(FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (var reader = new StreamReader(logFile))
                {
                    var line = reader.ReadLine();
                    if (!string.IsNullOrEmpty(line))
                    {
                        while (!reader.EndOfStream)
                        {
                            var nextLine = reader.ReadLine();
                            if (nextLine != null)
                            {
                                line = nextLine;
                                var fields = line.Split(new[] { '\t' });
                                var entry = new LogEntry(fields);
                                LogEntries.Add(entry);
                            }
                        }
                    }
                }
            }
        }
    }
}